//
//  PPTimelineDetailViewController.m
//  pickpic
//
//  Created by GaoYongyue on 16/9/25.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPTimelineDetailViewController.h"
#import "PPProfileViewController.h"
#import "PPCommentTimelineViewController.h"

#import "PPTimelineDetailHeaderView.h"
#import "PPTimelineDetailCommentView.h"

#import "PPCommentTimelineTableViewCell.h"

#import "PPAlbumShareView.h"
#import "PPAlbumShareActionView.h"

#import "PPSocializationManager.h"

static NSInteger const kCount = 50;
@interface PPTimelineDetailViewController () <PPTimelineDetailHeaderViewDelegate, PPCommentTimelineViewControllerDelegate>
@property (readwrite, nonatomic, strong) PPTimelineDetailHeaderView *headerView;
@property (readwrite, nonatomic, strong) PPTimelineDetailCommentView *commentView;
@property (nonatomic, strong) NSNumber *next; //-1不存在下一页
@property (readwrite, nonatomic, assign) CGFloat keyboardTop;
@property (readwrite, nonatomic, strong) UIControl *dismissalControl;
@end

@implementation PPTimelineDetailViewController

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    _keyboardTop = self.view.height;

    self.title = @"详情";

    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.tableView registerClass:[PPCommentTimelineTableViewCell class] forCellReuseIdentifier:@"commentCell"];

    _headerView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([PPTimelineDetailHeaderView class]) owner:nil options:nil][0];
    _headerView.album = _album;
    _headerView.delegateViewController = self;
    _headerView.delegate = self;
    _headerView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [PPTimelineDetailHeaderView heightForAlbum:_album]);

    _commentView = [[PPTimelineDetailCommentView alloc] init];
    [_commentView.sendButton addTarget:self action:@selector(sendButtonDidPressed) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_commentView];

    _dismissalControl = [[UIControl alloc] init];
    [_dismissalControl addTarget:self action:@selector(dismissalControlDidPressed) forControlEvents:UIControlEventTouchUpInside];
    _dismissalControl.hidden = YES;
    _dismissalControl.frame = self.view.bounds;
    [self.view addSubview:_dismissalControl];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillChangeFrameNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardWillShowNotification:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveKeyboardDidHideNotification:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)didReceiveKeyboardWillShowNotification:(NSNotification *)notification {
    _dismissalControl.hidden = NO;
}

- (void)didReceiveKeyboardDidHideNotification:(NSNotification *)notification {
    _dismissalControl.hidden = YES;
}

- (void)didReceiveKeyboardWillChangeFrameNotification:(NSNotification *)notification {
    CGRect endRect = [[notification.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSTimeInterval duration = [[notification.userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    UIViewAnimationCurve curve = [[notification.userInfo objectForKey:UIKeyboardAnimationCurveUserInfoKey] integerValue];

    CGRect rect = [[[UIApplication sharedApplication] keyWindow] convertRect:endRect toView:self.view];

    _keyboardTop = CGRectGetMinY(rect);

    [UIView animateWithDuration:duration delay:0 options:UIViewAnimationOptionBeginFromCurrentState|(curve << 16) animations:^{
        _commentView.bottom = _keyboardTop;
        _dismissalControl.height = _commentView.top;
    } completion:nil];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    _commentView.frame = CGRectMake(0, _keyboardTop - 46, self.view.width, 46);

    _dismissalControl.frame = CGRectMake(0, 0, self.view.width, _commentView.top);
}

- (void)fetchAlbumDetailsWithCompletion:(void (^)(NSDictionary *, NSError *))completion {
    __weak typeof(self)weakSelf = self;
    [PPNetworkService getAlbumDetailsByAlbumID:_album.albumID callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            !completion ? : completion(data, nil);
        } else {
            !completion ? : completion(nil, error);
        }
    }];
}

- (void)sendButtonDidPressed {
    if (_commentView.targetCommentID)
    {
        [MobClick event:@"113"];
    }
    [_commentView willSend];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService sendCommentWithType:@(1) ID:_album.albumID parentID:_commentView.targetCommentID ? : @(-1) content:_commentView.text version:nil callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {

            [strongSelf fetchNewItems];
        } else {
            [strongSelf.navigationController.view toastMessage:error.networkPrompt];
        }
    }];

    [_commentView didSend];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.items count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

    return [PPCommentTimelineTableViewCell heightForComment:comment constrainedSize:CGSizeMake(tableView.width, 1000)];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

    PPCommentTimelineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    cell.comment = comment;

    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

    _commentView.target = comment.sender;
    _commentView.targetCommentID = comment.commentID;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    PPUserID ownerID = _album.userID;

    if([ownerID isEqualToString:DGCurrentAccount.userID]) {
        return YES;
    } else {
        PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

        if([comment.sender.userID isEqualToString:DGCurrentAccount.userID]) {
            return YES;
        }
    }

    return NO;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if(editingStyle == UITableViewCellEditingStyleDelete) {
        PPTimelineCommentObject *comment = [self.items safeObjectAtIndex:indexPath.row];

        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

        __weak typeof(self)weakSelf = self;
        [PPNetworkService deleteCommentWithCommentID:comment.commentID type:@(1) callback:^(id data, NSError *error) {
            __strong typeof(weakSelf)strongSelf = weakSelf;

            if(strongSelf == nil) {
                return;
            }

            [hud hide:YES];

            if(error == nil) {
                [strongSelf fetchNewItems];
            } else {
                [strongSelf.navigationController.view toastMessage:error.networkPrompt];
            }
        }];
    }

    tableView.editing = NO;
}

#pragma mark - Timeline

- (UIEdgeInsets)preferredScrollInsets {
    return UIEdgeInsetsMake(64, 0, 46, 0);
}

- (NSArray *)initialItems {
    return nil;
}

- (void)fetchNewItems {
    [super fetchNewItems];

    _next = nil;
    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchCommentListWithType:@1 ID:_album.albumID start:_next limit:kCount version:nil callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchCommentListWithType:@1 ID:_album.albumID start:_next limit:kCount version:nil callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveMoreResult:data ? : error];
    }];
}
- (NSArray *)didReceiveNewResult:(id)result {

    self.tableView.tableHeaderView = _headerView;
    NSArray *items = [super didReceiveNewResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    NSArray *items = [super didReceiveMoreResult:result];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    return items;
}


- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    for(NSDictionary *parameter in [result validArrayForKey:@"comments"]) {
        PPTimelineCommentObject *comment = [PPTimelineCommentObject commentForParameters:parameter];

        NSString *content = nil;

        if(comment.receiver == nil) {
            content = comment.content;
        } else {
            content = [NSString stringWithFormat:@"回复 \u200C%@: %@", comment.receiver.name, comment.content];
        }

        DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
        editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
        editor.defaultFont = [UIFont systemFontOfSize:15];

        DGCoreTextPatternSetting *nameSetting = [[DGCoreTextPatternSetting alloc] init];
        nameSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
        nameSetting.defaultFont = [UIFont systemFontOfSize:15];
        nameSetting.highlightedFont = [UIFont systemFontOfSize:15];
        nameSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        nameSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        nameSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentReceiver:comment];
        };
        [editor preprocessWithPatternSetting:nameSetting];
        [editor process];

        comment.editor = editor;

        [items addObject:comment];
    }

    return items;
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

#pragma mark - Share

- (void)didSelectShareAlbum:(PPAlbumObject *)album {

    __block NSError *error_ = nil;
    __block NSString *title = nil;
    __block NSString *subtitle = nil;
    __block NSString *url = nil;
    __block UIImage *image_ = nil;
    __block NSString *pickpic = nil;

    dispatch_group_t group = dispatch_group_create();

    __weak typeof(self)weakSelf = self;

    dispatch_group_enter(group);
    [PPNetworkService getShareInfoWithAlbumID:album.albumID callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            title = [data validStringForKey:@"title"];
            subtitle = [data validStringForKey:@"title2"];
            url = [data validStringForKey:@"url"];
            pickpic = [data validStringForKey:@"pickpic"];
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);

    }];

    dispatch_group_enter(group);
    [album queryCoverImageWithCompletion:^(UIImage *image, NSError *error) {
        if(error == nil) {
            image_ = image;
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);
    }];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [hud hide:YES];

        if(error_ != nil) {
            [self.navigationController.view toastMessage:error_.networkPrompt];
        } else {
            [self shareAlbum:album title:title subtitle:subtitle url:url image:image_ pickpic:pickpic];
        }
    });
}

- (void)shareAlbum:(PPAlbumObject *)album title:(NSString *)title subtitle:(NSString *)subtitle url:(NSString *)url image:(UIImage *)image pickpic:(NSString *)pickpic {

    UIView *actionView = nil;

    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin] && [[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:4];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:5];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:6];
    } else {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:7];
    }

    UIView *displayView = self.navigationController.view;

    PPAlbumShareView *shareView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareView" owner:nil options:nil].firstObject;
    shareView.alpha = 0;
    shareView.frame = displayView.bounds;
    shareView.avatarURLString = album.ownerAvatar;
    shareView.name = album.ownerName;
    shareView.account = pickpic;
    shareView.cover = image;
    shareView.title = album.title;
    [displayView addSubview:shareView];

    shareView.titleLabel.hidden = YES;
    UIImage *thumbnail = [shareView.contentView snapshotImage];
    shareView.titleLabel.hidden = NO;
    image = [shareView.contentView snapshotImage];

    actionView.frame = CGRectMake(0, displayView.height - actionView.height, displayView.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:displayView contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleNone];

    __weak typeof(popoverView)weakPopover = popoverView;

    if([actionView respondsToSelector:@selector(wechatButton)]) {
        UIButton *wechatButton = [actionView valueForKey:@"wechatButton"];
        [wechatButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(circleButton)]) {
        UIButton *circleButton = [actionView valueForKey:@"circleButton"];
        [circleButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinCircle];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(weiboButton)]) {
        UIButton *weiboButton = [actionView valueForKey:@"weiboButton"];
        [weiboButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeibo];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(qqButton)]) {
        UIButton *qqButton = [actionView valueForKey:@"qqButton"];
        [qqButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{
                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeQQChat];
            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(cancelButton)]) {
        UIButton *cancelButton = [actionView valueForKey:@"cancelButton"];
        [cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    popoverView.willDisplayBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 1;
        } completion:nil];

    };

    popoverView.willDismissBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 0;
        } completion:^(BOOL finished) {
            [shareView removeFromSuperview];
        }];

    };

    [popoverView displayAnimated:YES completion:nil];
}

- (void)dismissalControlDidPressed {
    UITextField *textField = [_commentView valueForKey:@"textField"];
    [textField resignFirstResponder];
}

#pragma mark - Delegate

- (void)detailHeaderView:(PPTimelineDetailHeaderView *)detailHeaderView didSelectShareAlbum:(PPAlbumObject *)album {
    [self didSelectShareAlbum:album];
}

- (void)detailHeaderView:(PPTimelineDetailHeaderView *)detailHeaderView didSelectCommentListForAlbum:(PPAlbumObject *)album {
    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.delegate = self;
    [self.navigationController pushViewController:commentViewController animated:YES];
}

#pragma mark - PPCommentTimelineViewControllerDelegate

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didInsertComment:(PPTimelineCommentObject *)comment {
    [self fetchNewItems];
}

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didRemoveComment:(PPTimelineCommentObject *)comment {
    [self fetchNewItems];
}

@end
